#include "TextureTransform.h"
#include <QSGGeometry>
#include <QSGGeometryNode>
#include <QSGMaterial>
#include <QSGSimpleTextureNode>
#include <QSGTransformNode>
#include <QSGVertexColorMaterial>
#include "tool.h"
TextureTransformItem::TextureTransformItem(QQuickItem* parent)
    : Super(parent)
{
    setFlag(Super::ItemHasContents);
}

TextureTransformItem::~TextureTransformItem() { }

QSGNode* TextureTransformItem::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData* data)
{
    (void)data;
    QSGTransformNode*     node = nullptr;

    if (!oldNode)
    {
        auto   path = getImagePath(imgPath + QStringLiteral("qz.png"));
        QImage image(path);
        qWarning() << path << image.width() << image.height();

        auto texture = window()->createTextureFromImage(image);
        auto textureNode = new QSGSimpleTextureNode;
        textureNode->setTexture(texture);
        textureNode->setOwnsTexture(true);
//        textureNode->setRect(0, 0, image.width(), image.height());
        textureNode->setRect(0, 0, width(), height());
        textureNode->setFiltering(QSGTexture::Linear);

        node = new QSGTransformNode;
        node->appendChildNode(textureNode);
    }
    else
    {
        node = static_cast<QSGTransformNode*>(oldNode);
    }
    if (mAngleChanged)
    {
        mAngleChanged = false;
        QMatrix4x4 mat;
        mat.translate(width() / 2, height() / 2);
        mat.rotate(angle(), 0, 0, 1);
        mat.translate(-width() / 2, -height() / 2);
        node->setMatrix(mat);
        node->markDirty(QSGNode::DirtyMatrix);
    }
    return node;
}

int TextureTransformItem::angle() const
{
    return mAngle;
}

void TextureTransformItem::setAngle(int newAngle)
{
    if (mAngle == newAngle)
        return;
    mAngle = newAngle;
    emit angleChanged();
    mAngleChanged = true;
    update();
}
